//
//  DiagnoseChatController.m
//  EcmDoctor
//
//  Created by 张进 on 15/7/3.
//  Copyright (c) 2015年 张进. All rights reserved.
//

#import "DiagnoseChatController.h"
#import "AppUtils.h"
#import "KaiYaoViewController.h"

@interface DiagnoseChatController (){
    bool isKeyboardShowing;
    bool isExtraViewWillShow;
    bool isAlertViewShowing;
}

@end

@implementation DiagnoseChatController

@synthesize chatView,talkTextField,talkBar,tackExtraView,addExtraElementButton,sendTextButton;



-(void)showAlertView{

    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
                                @"确认要结束对话吗" message:@"" delegate:self
                                    cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [alertView show];
}

-(void)endChatConfirm:(id)sender{
    
    if (!isAlertViewShowing) {
        isAlertViewShowing = true;
        if (isKeyboardShowing) {
            [self.view endEditing:YES];
            [self performSelector:@selector(showAlertView) withObject:nil afterDelay:0.6];
        }else{
            [self performSelector:@selector(showAlertView) withObject:nil];
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:
(NSInteger)buttonIndex{
    if(alertView.tag==1989)
        [self performSegueWithIdentifier:@"prescibemedicine" sender:nil];
    else{
    isAlertViewShowing = false;
    switch (buttonIndex) {
        case 0:
            break;
        case 1:
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
            
            break;
        default:
            break;
    }}
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    isKeyboardShowing = false;
    isExtraViewWillShow = false;
    isAlertViewShowing = false;
    
    talkTextField.delegate = self;
    
    //左上角返回按钮
    UIImage *tableIcon = [UIImage imageNamed:@"btn_back"];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithImage:tableIcon style:UIBarButtonItemStylePlain target:self action:@selector(endChatConfirm:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithPatternImage:tableIcon];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        
        //需要注意的是self.isViewLoaded是必不可少的，其他方式访问视图会导致它加载 ，在WWDC视频也忽视这一点。
        
        if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
        
    }
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(IBAction)onEndChatButtonClicked:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(IBAction)onPrescribeButtonClicked:(id)sender{
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
                              @"选择方式" message:@"" delegate:self
                                             cancelButtonTitle:@"医保" otherButtonTitles: nil];
    alertView.tag=1989;
    [alertView show];

    
 
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  if([segue.identifier isEqualToString:@"prescibemedicine"])
    {
        KaiYaoViewController *kaiYao=segue.destinationViewController;
        kaiYao.user_name= self.name;
        kaiYao.user_age=self.age;
        kaiYao.user_sex=self.sex;
        kaiYao.user_icon=self.headIconUrl;
        NSLog(@"----------%@",self.headIconUrl);
        kaiYao.bqDesc=self.bqDesc;
        kaiYao.user_info_id=self.user_info_id;
        kaiYao.askId= self.askId;
        
    }
    
}

-(IBAction)onButtonAddExtraClicked:(id)sender{
    isExtraViewWillShow = true;
    
    NSLog(@"onButtonAddExtraClicked");
    
    if (isKeyboardShowing) {
        [self.view endEditing:YES];
        
    }else{
        CGFloat sHeight = self.chatView.frame.size.height;
        CGRect talkBarRect = self.talkBar.frame;
        if (talkBarRect.origin.y == sHeight - talkBarRect.size.height) {
            CGRect talkExtraViewRect = self.tackExtraView.frame;
            talkExtraViewRect.origin.y = sHeight;
            self.tackExtraView.frame = talkExtraViewRect;
            
            talkBarRect.origin.y = sHeight - talkBarRect.size.height;
            self.talkBar.frame = talkBarRect;
            
            CGRect talkExtraViewDestRect = CGRectMake(0, sHeight - talkExtraViewRect.size.height, talkExtraViewRect.size.width, talkExtraViewRect.size.height);
            CGRect talkBarDestRect = CGRectMake(0, sHeight - talkExtraViewRect.size.height - talkBarRect.size.height, talkBarRect.size.width, talkBarRect.size.height);
            
            [UIView animateWithDuration:0.3 animations:^{
                self.talkBar.frame = talkBarDestRect;
                self.tackExtraView.frame = talkExtraViewDestRect;
            } completion:^(BOOL finished){
                isExtraViewWillShow = false;
            }];
        }
        
        
    }
}
-(IBAction)onButtonSendTextClicked:(id)sender{
    NSLog(@"onButtonSendTextClicked");
}
-(IBAction)onButtonVoiceClicked:(id)sender{
    NSLog(@"onButtonVoiceClicked");
    
    if (isKeyboardShowing) {
        [self.view endEditing:YES];
    }else{
        CGFloat sHeight = self.chatView.frame.size.height;
        CGRect talkExtraViewRect = self.tackExtraView.frame;
        if (talkExtraViewRect.origin.y < sHeight) {
            CGRect destRect = CGRectMake(0, sHeight-self.talkBar.frame.size.height, self.talkBar.frame.size.width, self.talkBar.frame.size.height);
            
            talkExtraViewRect.origin.y = sHeight;
            
            [UIView animateWithDuration:0.2 animations:^{
                self.talkBar.frame = destRect;
                self.tackExtraView.frame = talkExtraViewRect;
            }];
        }
    }
    
}

-(IBAction)onTalkTextFieldEditChanged:(id)sender{
    NSLog(@"onTalkTextFieldValueChanged");
    
}


#pragma UITextFieldDelegate

//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
//    CGRect frame = textField.frame;
////    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//键盘高度216
//    
//    int offset = talkBar.frame.origin.y + 50 - 216.0;
//    
//    
//    NSTimeInterval animationDuration = 0.30f;
//    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
//    [UIView setAnimationDuration:animationDuration];
//    
//    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
////    if(offset < 0)
//        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
//    
//    [UIView commitAnimations];
}

//当用户按下return键或者按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
//    [textField resignFirstResponder];
    return YES;
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
//    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}


-(void)viewWillAppear:(BOOL)animated
{
    [self regNotification];
    
//    CGFloat sHeight = self.chatView.frame.size.height;
//    CGRect talkExtraViewRect = self.tackExtraView.frame;
//    talkExtraViewRect.origin.y = sHeight;
//    self.tackExtraView.frame = talkExtraViewRect;
//
//    CGRect talkBarRect = self.talkBar.frame;
//    talkBarRect.origin.y = sHeight - talkBarRect.size.height;
//    self.talkBar.frame = talkBarRect;
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [self unregNotification];
}


- (void)regNotification
{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)unregNotification
{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}





#pragma mark - notification handler

- (void)keyboardWillShow:(NSNotification *)notification{
    isKeyboardShowing = true;
    
    NSDictionary *info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
//    CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat height = endKeyboardRect.size.height;
//    NSLog(@"keyboardWillShow,beginY:%f;endY:%f;height:%f",beginKeyboardRect.origin.y,endKeyboardRect.origin.y,height);
    
    CGFloat sHeight = self.chatView.frame.size.height;
    CGRect destRect = CGRectMake(0, sHeight-height-50, self.talkBar.frame.size.width, self.talkBar.frame.size.height);
    
    CGRect talkExtraViewRect = self.tackExtraView.frame;
    talkExtraViewRect.origin.y = sHeight-height;
    
    [UIView animateWithDuration:duration animations:^{
        self.talkBar.frame = destRect;
        self.tackExtraView.frame = talkExtraViewRect;
    }];
    
    //发送按钮显示
    self.sendTextButton.hidden = NO;
    //添加按钮隐藏
    self.addExtraElementButton.hidden = YES;
}
- (void)keyboardWillHide:(NSNotification *)notification{
    isKeyboardShowing = false;
    
    NSDictionary *info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
//    CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
//    CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    
    if (isExtraViewWillShow) {
        CGFloat sHeight = self.chatView.frame.size.height;
        CGRect destRect = CGRectMake(0, sHeight-self.talkBar.frame.size.height-self.tackExtraView.frame.size.height, self.talkBar.frame.size.width, self.talkBar.frame.size.height);
        
        CGRect talkExtraViewRect = self.tackExtraView.frame;
        talkExtraViewRect.origin.y = self.talkBar.frame.origin.y + self.talkBar.frame.size.height;
        self.tackExtraView.frame = talkExtraViewRect;
        talkExtraViewRect.origin.y = sHeight - self.tackExtraView.frame.size.height;
        
        [UIView animateWithDuration:duration animations:^{
            self.talkBar.frame = destRect;
            self.tackExtraView.frame = talkExtraViewRect;
        }];
        isExtraViewWillShow = false;
    }else{
        CGFloat sHeight = self.chatView.frame.size.height;
        CGRect destRect = CGRectMake(0, sHeight-self.talkBar.frame.size.height, self.talkBar.frame.size.width, self.talkBar.frame.size.height);
        
        CGRect talkExtraViewRect = self.tackExtraView.frame;
        talkExtraViewRect.origin.y = sHeight;
        
        [UIView animateWithDuration:duration animations:^{
            self.talkBar.frame = destRect;
            self.tackExtraView.frame = talkExtraViewRect;
        }];
    }
    
    //发送按钮显示
    self.sendTextButton.hidden = true;
    //添加按钮隐藏
    self.addExtraElementButton.hidden = false;
}

@end
